//
//  MineFocusViewController.swift
//  House
//
//  Created by 吕品 on 2016/9/2.
//  Copyright © 2016年 ZJWL. All rights reserved.
//

import MBProgressHUD
import UIKit

class MineFocusViewController: BaseViewController, UITableViewDataSource, UITableViewDelegate {
    fileprivate var seg = UISegmentedControl.init(items: ["二手房", "租房"])
    fileprivate var scrollView = UIScrollView.init()
    fileprivate var tableViewArray = [UITableView]()
    fileprivate var dataArray = [[AnyObject]]()
    fileprivate var rentArray = [RentHouseListModel]()
    fileprivate var buyArray = [SecondaryListModel]()
    open var contentType: Int = 0 //0 关注 1 浏览历史
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        navigationController?.isNavigationBarHidden = false
        tabBarController?.tabBar.isHidden = true
    }
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        navigationController?.isNavigationBarHidden = true
    }
    //MARK: Seg func
    func didSelecetSeg(_ seg: UISegmentedControl) -> Swift.Void {
        scrollView.setContentOffset(CGPoint.init(x: UIScreen.main.bounds.size.width
             * CGFloat.init(seg.selectedSegmentIndex), y: 0), animated: true)
        if contentType == 0 {
            requsetDataWithHouseType(seg.selectedSegmentIndex + 1)
        } else {
            if seg.selectedSegmentIndex == 0 {
                requsetDataWithHouseType(5)
            } else {
                requsetDataWithHouseType(7)
            }
        }
    }

    deinit {
        seg.isHidden = true
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        dataArray = [rentArray, buyArray]
        automaticallyAdjustsScrollViewInsets = false
        seg.addTarget(self, action: #selector(MineFocusViewController.didSelecetSeg(_:)), for: .valueChanged)
        navigationController?.navigationItem.rightBarButtonItem = editButtonItem
        navigationController?.navigationBar.addSubview(seg)
        seg.selectedSegmentIndex = 0
        seg.snp.makeConstraints { (make) in
            make.center.equalTo((navigationController?.navigationBar)!)
            make.height.equalTo(30)
            make.width.equalTo(160)
        }
        createTableView()
        didSelecetSeg(seg)
        // Do any additional setup after loading the view.
    }
    private func createTableView() -> Swift.Void {
        view.addSubview(scrollView)
        scrollView.snp.makeConstraints { (make) in
            make.top.equalTo(view).offset(64)
            make.left.right.bottom.equalTo(view)
        }
        scrollView.contentSize = .init(width: UIScreen.main.bounds.size.width * 2, height: 0)
        scrollView.showsVerticalScrollIndicator = false
        scrollView.showsHorizontalScrollIndicator = false
        scrollView.delegate = self
        scrollView.isPagingEnabled = true
        for i in 0 ... 1 {
            let width = UIScreen.main.bounds.size.width
            let height = UIScreen.main.bounds.size.height
            let tableView = UITableView.init(frame: CGRect.init(x: width * CGFloat.init(i), y: 0, width: width, height: height - 64), style: .plain)
            tableView.tableFooterView = UIView.init()
            scrollView.addSubview(tableView)
            tableViewArray.append(tableView)
            tableView.delegate = self
            tableView.dataSource = self
            if i % 2 == 0 {
                tableView.register(SecondaryHouseListNoSlideTableViewCell.self, forCellReuseIdentifier: NSStringFromClass(SecondaryHouseListNoSlideTableViewCell.self))
            } else {
                tableView.register(RentHouseListNoSlideTableViewCell.self, forCellReuseIdentifier: NSStringFromClass(RentHouseListNoSlideTableViewCell.self))
            }
        }
    }
    //MARK: tableView dataSource
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        let index = tableViewArray.index(of: tableView)!
        return dataArray[index].count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let index = tableViewArray.index(of: tableView)!
        if index % 2 == 0 {
            let buyCell = tableView.dequeueReusableCell(withIdentifier: NSStringFromClass(SecondaryHouseListNoSlideTableViewCell.self)) as! SecondaryHouseListNoSlideTableViewCell
            buyCell.model = dataArray[index][indexPath.row] as! SecondaryListModel
            buyCell.selectionStyle = .none
            return buyCell
        } else {
            let rentCell = tableView.dequeueReusableCell(withIdentifier: NSStringFromClass(RentHouseListNoSlideTableViewCell.self))
                as! RentHouseListNoSlideTableViewCell
            rentCell.model = dataArray[index][indexPath.row] as! RentHouseListModel
            rentCell.selectionStyle = .none
            return rentCell
        }
    }
    //MARK: DataRequset
    private func requsetDataWithHouseType(_ type: Int) -> Swift.Void {
        let hud = MBProgressHUD.showAdded(to: view, animated: true)
        hud.label.text = "加载中"
        hud.backgroundView.style = .blur
        hud.backgroundView.backgroundColor = .white
        hud.bezelView.style = .blur
        hud.animationType = .zoomIn
        let uid = UserInfoManager.shared().uid!
        var urlString = ""
        if contentType == 0 { //关注 1卖 2租
            urlString = String.init(format: "http://aizufang.hrbzjwl.com/tp/api.php/Iosapp/follow_select/uid/%@/type/%d", uid, type)
        } else { //浏览 5 卖 7租
            var idStr = ""
            let arr = MineHistoryManager.getInfoWithType(type, andNumber: 20) as! [String]
            for str in arr {
                idStr.append(str)
                idStr.append(",")
            }
            urlString = String.init(format: "http://aizufang.hrbzjwl.com/tp/api.php/Index/liulan/id/%@/type/%d", idStr, type)
        }
        print(urlString)
        NetRequest.getInformationWithGetMethod(withUrl: urlString, success: { (task, response) in
            print(response)
            if type == 1 || type == 5 {
                if response is NSDictionary {
                    let responseObj = response as! NSDictionary
                    if (responseObj["flag"] as! NSNumber).description == "1" {
                        if self.contentType == 0 {
                            self.dataArray[0] = SecondaryListModel.setValuesAndKeysWith(responseObj["data"] as! [[AnyHashable: Any]]) as! [SecondaryListModel]
                        } else {
                            self.dataArray[0] = SecondaryListModel.setValuesAndKeysWith(responseObj["content"] as! [[AnyHashable: Any]]) as! [SecondaryListModel]
                        }
                    }
                    else {
                        self.hide(withTitle: "暂无数据")
                        return
                    }
                }
            } else {
                if response is NSDictionary {
                    let responseObj = response as! NSDictionary
                    if (responseObj["flag"] as! NSNumber).description == "1" {
                        if self.contentType == 0 {
                            self.dataArray[1] = RentHouseListModel.setValuesAndKeysWith(responseObj["data"] as! [[AnyHashable: Any]]) as! [RentHouseListModel]
                        } else {
                            self.dataArray[1] = RentHouseListModel.setValuesAndKeysWith(responseObj["content"] as! [[AnyHashable: Any]]) as! [RentHouseListModel]
                        }
                    } else {
                        self.hide(withTitle: "暂无数据")
                        return
                    }

                }
            }
            for tableView in self.tableViewArray {
                tableView.reloadData()
            }
            self.hide(withTitle: "加载完成")
            }) { (task, error) in
                print(error)
        }
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let index = tableViewArray.index(of: tableView)!
        if index == 0 {
            let secondaryVC = RentHouseDetailViewController.init()
            let model = dataArray[index][indexPath.row] as! SecondaryListModel
            secondaryVC.itemid = model.itemid!
            navigationController!.pushViewController(secondaryVC, animated: true)
        } else {
            let rentVC = SecondaryDetailViewController.init()
            let model = dataArray[index][indexPath.row] as! RentHouseListModel
            rentVC.itemID = model.itemid
            navigationController!.pushViewController(rentVC, animated: true)
        }
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 120
    }
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        if scrollView.isEqual(self.scrollView) {
            let index = scrollView.contentOffset.x / UIScreen.main.bounds.size.width
            seg.selectedSegmentIndex = Int.init(index)
            didSelecetSeg(seg)
        }
    }

}
